<template>
  <view class="page">
    <!-- 自定义任务选项卡 -->
    <view class="custom-tabs">
      <view
        class="tab-item"
        :class="{ active: model_currentTab === 0 }"
        @click="sTab(0)"
      >
        待接任务
      </view>
      <view
        class="tab-item"
        :class="{ active: model_currentTab === 1 }"
        @click="sTab(1)"
      >
        进行中
      </view>
      <view
        class="tab-item"
        :class="{ active: model_currentTab === 2 }"
        @click="sTab(2)"
      >
        已完成
      </view>
      <view class="tab-line" :style="tabLineStyle"></view>
    </view>

    <!-- 任务内容 -->
    <swiper
      class="swiper"
      :current="currentTab"
      @change="swiperChange"
      :duration="300"
    >
      <swiper-item>
        <scroll-view class="scroll-view" scroll-y>
          <view class="task-card" v-for="(task, index) in tasks" :key="index">
            <view class="task-header">
              <h3 class="task-title">{{ task.title }}</h3>
              <view class="task-status status-pending">{{
                statusText(task.status)
              }}</view>
            </view>
            <view class="task-body">
              <view class="task-detail">
                <u-icon name="map" color="#3498db" size="18"></u-icon>
                <text>{{ task.departureLocation }}-{{ task.destination }}</text>
              </view>
              <view class="task-detail">
                <u-icon name="clock" color="#3498db" size="18"></u-icon>
                <text
                  >{{ fmtTime(task.startTime) }}-{{
                    fmtTime(task.endTime)
                  }}</text
                >
              </view>
              <view class="task-detail">
                <u-icon name="account" color="#3498db" size="18"></u-icon>
                <text>{{ task.passengers }}</text>
              </view>
              <view class="task-detail">
                <u-icon name="car" color="#3498db" size="18"></u-icon>
                <text>{{ task.plateNumber }}</text>
              </view>
            </view>
            <view class="task-actions">
              <u-button
                size="mini"
                type="default"
                plain
                @click="viewTaskDetail(task)"
                >查看详情</u-button
              >
              <!-- 仅在待接任务时显示“开始任务” -->
              <!-- 订单状态：dispatched-已派车，in_progress-进行中，completed-已完成，cancelled-已取消 -->
              <u-button
                v-if="task.status === 'dispatched'"
                size="mini"
                type="primary"
                @click="acceptTask(task)"
              >
                开始任务
              </u-button>
              <u-button
                v-if="task.status === 'in_progress'"
                size="mini"
                type="primary"
                @click="completedTask(task)"
              >
                完成任务
              </u-button>
            </view>
          </view>

          <!-- 空状态提示 -->
          <view class="empty-tips" v-if="tasks.length === 0">
            <u-icon name="list" size="60" color="#ccc"></u-icon>
            <text>暂无任务</text>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!-- 底部 tabbar -->
    <u-tabbar
      :value="currentTab"
      :placeholder="false"
      :safeAreaInsetBottom="false"
    >
      <u-tabbar-item
        v-for="(item, index) in tabBarList"
        :key="index"
        :text="item.text"
        :name="item.text"
        @click="handTab(item)"
      >
        <image
          class="bar_img"
          slot="active-icon"
          :src="item.selectedIconPath"
        ></image>
        <image
          class="bar_img"
          slot="inactive-icon"
          :src="item.iconPath"
        ></image>
      </u-tabbar-item>
    </u-tabbar>
  </view>
</template>

<script>
import { formatTaskTime } from "@/utils/formatTaskTime.js";

export default {
  data() {
    return {
      tabBarList: this.$store.state.dynamicTabbar,
      currentTab: 0,
      model_currentTab: 0,
      currentBottomTab: "任务",
      tabLineStyle: "transform: translateX(0); width: 33.33%;",
      tasks: [],
    };
  },
  onShow() {
    this.sTab(0);

    console.log(this.tabBarList);
  },
  methods: {
    fmtTime: formatTaskTime,
    statusText(status) {
      const map = {
        dispatched: "待接取",
        in_progress: "进行中",
        completed: "已完成",
        cancelled: "已取消",
      };
      return map[status] || status;
    },
    async getTaskList(status) {
      const res = await uni.$http.get("/sys/orders/dispatchTask", { status });
      this.tasks = res.data.data || [];
    },
    handTab(row) {
      uni.switchTab({ url: row.pagePath });
    },
    sTab(index) {
      const statusMap = ["dispatched", "in_progress", "completed"];
      this.currentTab = index;
      this.model_currentTab = index;
      this.updateTabLine(index);
      this.getTaskList(statusMap[index]);
    },
    swiperChange(e) {
      const index = e.detail.current;
      const statusMap = ["dispatched", "in_progress", "completed"];
      this.currentTab = index;
      this.model_currentTab = index;
      this.updateTabLine(index);
      this.getTaskList(statusMap[index]);
    },
    updateTabLine(index) {
      const translateX = index * 100;
      this.tabLineStyle = `transform: translateX(${translateX}%); width: 33.33%;`;
    },
    async acceptTask(task) {
      uni.showModal({
        title: "确认开始",
        content: `确定要开始“${task.title}”任务吗？`,
        success: async (res) => {
          // ← 这里加 async
          if (res.confirm) {
            try {
              const res = await uni.$http.put(
                `/sys/orders/startTask/${task.id}`
              );
              uni.showToast({ title: res.data.message, icon: "success" });
              this.sTab(1);
            } catch (e) {
              uni.showToast({ title: "操作失败", icon: "none" });
            }
          }
        },
      });
    },
    viewTaskDetail(task) {
      uni.navigateTo({ url: `/pages/taskDetail/taskDetail?id=${task.id}` });
    },
    completedTask(task) {
      uni.navigateTo({
        url: `/pages/taskComplete/taskComplete?id=${task.id}`,
      });
    },
  },
  mounted() {
    this.updateTabLine(this.currentTab);
  },
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #f5f9ff;
  min-height: 100vh;
  padding-bottom: 100px;
}
.custom-tabs {
  display: flex;
  background-color: white;
  position: relative;
  border-bottom: 1px solid #eee;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 30rpx;
  color: #666;
  transition: color 0.3s;
  &.active {
    color: #3498db;
    font-weight: bold;
  }
}
.tab-line {
  position: absolute;
  bottom: 0;
  height: 4rpx;
  background-color: #3498db;
  transition: transform 0.3s;
}
.task-card {
  background-color: white;
  margin: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 10rpx rgba(52, 152, 219, 0.1);
  overflow: hidden;
}
.task-header {
  padding: 30rpx;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.task-title {
  font-weight: bold;
  margin: 0;
  font-size: 32rpx;
}
.task-status {
  padding: 6rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}
.status-pending {
  background-color: #e3f2fd;
  color: #1976d2;
}
.task-body {
  padding: 30rpx;
}
.task-detail {
  display: flex;
  margin-bottom: 20rpx;
  align-items: center;
  text {
    margin-left: 20rpx;
  }
}
.task-actions {
  padding: 20rpx 30rpx;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
}
.swiper {
  height: calc(100vh - 380rpx);
}
.scroll-view {
  height: 100%;
}
.empty-tips {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
  text {
    margin-top: 20rpx;
    font-size: 28rpx;
  }
}
.bar_img {
  width: 54rpx;
  height: 54rpx;
}
</style>
